package controllers

import (
	"anban/logic"
	"anban/service"
	"anban/utils"
	"fmt"
	"github.com/astaxie/beego"
	"github.com/astaxie/beego/logs"
	"net/url"
	"time"
)

type BindRes struct {
	Error        int         `json:"error"`
	ErrorMessage string      `json:"errorMessage"`
	DeviceId     string      `json:"deviceId"`
	SchoolId     string      `json:"schoolId"`
	SchoolName   string      `json:"schoolName"`
	Place        []BindPlace `json:"place"`
}

type BindPlace struct {
	Tid  string `json:"tid"`
	Name string `json:"name"`
}

type ActiveRes struct {
	Error        int    `json:"error"`
	ErrorMessage string `json:"errorMessage"`
}

type AdpicsRes struct {
	Error        int      `json:"error"`
	ErrorMessage string   `json:"errorMessage"`
	Pics         []Adpics `json:"pics"`
}

type Adpics struct {
	Id    string `json:"id"`
	Photo string `json:"photo"`
	Title string `json:"title"`
}

type UploadLogRes struct {
	Error        int    `json:"error"`
	ErrorMessage string `json:"errorMessage"`
}

type InfosRes struct {
	Error        int     `json:"error"`
	ErrorMessage string  `json:"errorMessage"`
	Infos        []Infos `json:"infos"`
}

type Infos struct {
	Mjauth    bool           `json:"mjauth"`
	StudentId string         `json:"studentId"`
	ObjId     string         `json:"objId"`
	CartNum   string         `json:"cartNum"`
	ClassId   string         `json:"classId"`
	Name      string         `json:"name"`
	ClassName string         `json:"className"`
	Photo     string         `json:"photo"`
	Sex       int            `json:"sex"`
	Parents   []InfosParents `json:"parents"`
}

type InfosParents struct {
	Name     string `json:"name"`
	Photo    string `json:"photo"`
	Relation string `json:"relation"`
}

type UnbindRes struct {
	Error        int    `json:"error"`
	ErrorMessage string `json:"errorMessage"`
}

type DoPlaceRes struct {
	Error        int    `json:"error"`
	ErrorMessage string `json:"errorMessage"`
}

type DeviceController struct {
	beego.Controller
}

func (c *DeviceController) Prepare() {
	c.EnableXSRF = false
}

// 设备登录（关联学校）
func (c *DeviceController) Bind() {
	res := &BindRes{}
	userName := c.GetString("username")
	password := c.GetString("password")
	deviceCode := c.GetString("deviceCode")
	mac := c.GetString("mac")

	res.Place = []BindPlace{}

	logs.Info("username:", userName, "password:", password, "deviceCode:", deviceCode, "mac:", mac)

	if len(userName) <= 0 || len(password) <= 0 {
		res.Error = 1000
		res.ErrorMessage = "操作失败，请提供用户名或密码"
		c.Data["json"] = res
		c.ServeJSON()
		return
	}

	p := map[string]interface{}{}
	p["relation"] = true
	p["username"] = userName
	p["password"] = password
	device := service.GetDeviceInfo(p)
	if device.Id <= 0 {
		res.Error = 1001
		res.ErrorMessage = "操作失败，请检查用户名或密码"
		c.Data["json"] = res
		c.ServeJSON()
		return
	}

	res.Error = 0
	res.ErrorMessage = ""
	res.SchoolName = device.School.Name
	res.SchoolId = device.School.Sn
	res.DeviceId = device.Sn
	res.Place = []BindPlace{
		{Tid: utils.GetRandomString(32), Name: device.Place},
	}

	if device.BindStatus != 1 {
		input := url.Values{
			"id":          {fmt.Sprintf("%d", device.Id)},
			"bind_status": {"1"},
			"device_code": {deviceCode},
			"mac":         {mac},
		}
		service.EditDevice(input)
	}

	c.Data["json"] = res
	c.ServeJSON()
}

// 考勤机心跳
func (c *DeviceController) Active() {
	res := &ActiveRes{}
	c.Data["json"] = res
	c.ServeJSON()
}

// 考勤机海报
func (c *DeviceController) Adpics() {
	res := &AdpicsRes{}
	deviceSn := c.GetString("deviceId")

	res.Pics = []Adpics{}

	if len(deviceSn) <= 0 {
		res.Error = 1000
		res.ErrorMessage = "参数提供不完整"
		c.Data["json"] = res
		c.ServeJSON()
		return
	}

	p := map[string]interface{}{}
	p["sn"] = deviceSn
	device := service.GetDeviceInfo(p)
	if device.Id <= 0 {
		res.Error = 1001
		res.ErrorMessage = "系统中没有找到对应设备"
		c.Data["json"] = res
		c.ServeJSON()
		return
	}

	var pics []Adpics
	p = map[string]interface{}{}
	p["deviceId"] = device.Id
	_, devicePictureList := service.GetDevicePictureList(p)

	for _, devicePicture := range  devicePictureList {
		adpics := Adpics{
			Id:    fmt.Sprintf("%d", devicePicture.Id),
			Photo: devicePicture.Url,
			Title: devicePicture.Title,
		}
		pics = append(pics, adpics)
	}

	res.Pics = pics
	c.Data["json"] = res
	c.ServeJSON()
}

// 上传打卡日志
func (c *DeviceController) UploadLog() {
	params := c.Input()
	logs.Info("uploadlog ", "params:", params)
	res := &UploadLogRes{}
	deviceSn := c.GetString("deviceId")
	schoolSn := c.GetString("schoolId")
	cardNum := c.GetString("cardNum")
	direction := c.GetString("direction")
	temp := c.GetString("temp")
	fTemp := utils.Atof64(temp)
	temp = fmt.Sprintf("%.1f", fTemp)
	logs.Info("uploadlog ", "cardNum:", cardNum, "direction:", direction, "schoolSn:", schoolSn, "temp:", temp)

	if len(deviceSn) <= 0 || len(schoolSn) <= 0 || len(cardNum) <= 0 || len(direction) <= 0 {
		res.Error = 1000
		res.ErrorMessage = "参数提供不完整"
		c.Data["json"] = res
		c.ServeJSON()
		return
	}
	p := map[string]interface{}{}
	p["sn"] = deviceSn
	device := service.GetDeviceInfo(p)
	if device.Id <= 0 {
		res.Error = 1001
		res.ErrorMessage = "系统中没有找到对应设备"
		c.Data["json"] = res
		c.ServeJSON()
		return
	}
	p = map[string]interface{}{}
	p["sn"] = schoolSn
	school := service.GetSchoolInfo(p)
	if school.Id <= 0 {
		res.Error = 1002
		res.ErrorMessage = "系统中没有找到对应学校"
		c.Data["json"] = res
		c.ServeJSON()
		return
	}
	p = map[string]interface{}{}
	p["relation"] = true
	p["sn"] = cardNum
	student := service.GetStudentInfo(p)
	if student.Id <= 0 {
		res.Error = 1003
		res.ErrorMessage = "系统中没有找到对应学生"
		c.Data["json"] = res
		c.ServeJSON()
		return
	}
	if student.Status == 0 {
		res.Error = 1004
		res.ErrorMessage = fmt.Sprintf("%s已被禁用", student.RealName)
		c.Data["json"] = res
		c.ServeJSON()
		return
	}

	var input url.Values
	input = url.Values{
		"device_id":  {fmt.Sprintf("%d", device.Id)},
		"school_id":  {fmt.Sprintf("%d", school.Id)},
		"student_id": {fmt.Sprintf("%d", student.Id)},
		"device_sn":  {deviceSn},
		"school_sn":  {schoolSn},
		"card_num":   {cardNum},
		"direction":  {direction},
		"temp":       {temp},
	}
	service.AddMfcardUploadLog(input)

	remark := ""

	if school.IsUseAccessControl == 1 {
		p = map[string]interface{}{}
		p["deviceId"] = device.Id
		p["studentId"] = student.Id
		p["isLeft"] = 0
		p["createdDate"] = time.Now().Format("2006-01-02")
		safeNotice := service.GetSafeNoticeInfo(p)

		if safeNotice.Id > 0 {

			if direction == "2" {
				input = url.Values{
					"id":      {fmt.Sprintf("%d", safeNotice.Id)},
					"is_left": {"1"},
					"left":    {time.Now().Format("2006-01-02 15:04:05")},
				}
				service.EditSafeNotice(input)

				input = url.Values{
					"id":           {fmt.Sprintf("%d", student.Id)},
					"is_at_school": {"0"},
				}
				service.EditStudent(input)

				input = url.Values{
					"student_id": {fmt.Sprintf("%d", student.Id)},
					"type":       {"1"},
				}
				service.AddNewNotice(input)

				go logic.SendAccessControlWechatNotice(student, "离校", remark)
			}

		} else {

			if direction == "1" {
				input = url.Values{
					"device_id":  {fmt.Sprintf("%d", device.Id)},
					"student_id": {fmt.Sprintf("%d", student.Id)},
					"is_arrived": {"1"},
					"arrived":    {time.Now().Format("2006-01-02 15:04:05")},
				}
				service.AddSafeNotice(input)

				input = url.Values{
					"id":           {fmt.Sprintf("%d", student.Id)},
					"is_at_school": {"1"},
				}

				input = url.Values{
					"student_id": {fmt.Sprintf("%d", student.Id)},
					"type":       {"1"},
				}
				service.AddNewNotice(input)

				go logic.SendAccessControlWechatNotice(student, "到校", remark)
			}

		}
	}

	if fTemp > 0 {
		var first string
		if direction == "1" {
			first = "您孩子到校体温异常"
		} else if direction == "2" {
			first = "您孩子离校体温异常"
		}

		input = url.Values{
			"id": {fmt.Sprintf("%d", student.Id)},
		}
		if fTemp > 37.0 {
			input["temp_is_normal"] = []string{"0"}

			if school.IsUseMobileMsg == 1 {
				go logic.SendTempAbnormalNotice(student, first, temp, "")
			}
		} else {
			input["temp_is_normal"] = []string{"1"}
		}
		service.EditStudent(input)

		if school.IsUseTemp == 1 {
			if direction == "1" {
				input = url.Values{
					"device_id":    {fmt.Sprintf("%d", device.Id)},
					"student_id":   {fmt.Sprintf("%d", student.Id)},
					"is_arrived":   {"1"},
					"arrived":      {time.Now().Format("2006-01-02 15:04:05")},
					"arrived_temp": {temp},
				}
				service.AddTempNotice(input)

				go logic.SendTempNotice(student, "离校体温通知", temp, "")
			} else if direction == "2" {
				p = map[string]interface{}{}
				p["deviceId"] = device.Id
				p["studentId"] = student.Id
				p["isLeft"] = 0
				p["createdDate"] = time.Now().Format("2006-01-02")

				v := map[string]interface{}{}
				v["is_left"] = 1
				v["left"] = time.Now().Format("2006-01-02 15:04:05")
				v["left_temp"] = temp

				service.EditTempNotices(p, v)

				go logic.SendTempNotice(student, "到校体温通知", temp, "")
			}
		}
	}

	res.Error = 0
	res.ErrorMessage = ""
	logs.Info("uploadlog ", "res:", res)
	c.Data["json"] = res
	c.ServeJSON()
}

// 获取平台卡号
func (c *DeviceController) Infos() {
	//input := c.Input()
	//logs.Info("deviceinfos", input)
	res := &InfosRes{}
	cardNum := c.GetString("cardNum")
	schoolSn := c.GetString("schoolId")
	res.Infos = []Infos{}
	if len(cardNum) <= 0 && len(schoolSn) <= 0 {
		res.Error = 1000
		res.ErrorMessage = "请提供卡号或学校ID"
		c.Data["json"] = res
		c.ServeJSON()
		return
	}
	if len(cardNum) > 1 {
		p := map[string]interface{}{}
		p["relation"] = true
		p["sn"] = cardNum
		student := service.GetStudentInfo(p)
		if student.Id > 0 {
			res.Error = 0
			res.ErrorMessage = ""
			res.Infos = []Infos{
				{
					Mjauth:    false,
					StudentId: student.Sn,
					ObjId:     student.Sn,
					CartNum:   student.Sn,
					ClassId:   student.Class.Sn,
					Name:      student.RealName,
					ClassName: student.Class.Name,
					Photo:     "",
					Sex:       student.Sex,
					Parents:   []InfosParents{},
				},
			}
		}
		c.Data["json"] = res
		c.ServeJSON()
		return
	}
	p := map[string]interface{}{}
	p["relation"] = true
	p["status"] = 1
	p["schoolSn"] = schoolSn
	_, studentList := service.GetStudentList(p)
	infos := []Infos{}
	for _, student := range studentList {
		t := Infos{
			Mjauth:    false,
			StudentId: student.Sn,
			ObjId:     student.Sn,
			CartNum:   student.Sn,
			ClassId:   student.Class.Sn,
			Name:      student.RealName,
			ClassName: student.Class.Name,
			Photo:     "",
			Sex:       student.Sex,
			Parents:   []InfosParents{},
		}
		infos = append(infos, t)
	}
	//logs.Info("deviceinfosres:", res)
	res.Infos = infos
	c.Data["json"] = res
	c.ServeJSON()
}

func (c *DeviceController) DoPlace() {
	res := &DoPlaceRes{}
	c.Data["json"] = res
	c.ServeJSON()
}

// 设备退出（注销关联学校）
func (c *DeviceController) Unbind() {
	res := &UnbindRes{}
	userName := c.GetString("username")
	password := c.GetString("password")

	if len(userName) <= 0 || len(password) <= 0 {
		res.Error = 1000
		res.ErrorMessage = "操作失败，请提供用户名或密码"
		c.Data["json"] = res
		c.ServeJSON()
		return
	}

	p := map[string]interface{}{}
	p["relation"] = true
	p["username"] = userName
	p["password"] = password
	device := service.GetDeviceInfo(p)
	if device.Id <= 0 {
		res.Error = 1001
		res.ErrorMessage = "操作失败，系统中没有找到此设备"
		c.Data["json"] = res
		c.ServeJSON()
		return
	}
	if device.BindStatus <= 0 {
		res.Error = 1002
		res.ErrorMessage = "操作失败，此设备没有绑定任何学校，无需解绑"
		c.Data["json"] = res
		c.ServeJSON()
		return
	}

	input := url.Values{
		"id":          {fmt.Sprintf("%d", device.Id)},
		"bind_status": {"0"},
		"device_code": {""},
		"mac":         {""},
	}
	service.EditDevice(input)

	res.Error = 0
	res.ErrorMessage = ""
	c.Data["json"] = res
	c.ServeJSON()
}
